﻿<template>
    <my-dialog v-model="state.dlgVisible" title="选择地址">
        <div class="index" style="height: 500px">
            <div style="height: 33px; position: relative; width: 100%">
                <el-input
                    v-model="search"
                    
                    clearable
                    type="text"
                    text
                    ref="place"
                    @keyup.enter="handleSearch"
                    placeholder="请输入地点"
                >
                    <template #append>
                        <el-button
                            icon="el-icon-search"
                            @click="handleSearch"
                        ></el-button>
                    </template>
                </el-input>
            </div>
            <div class="map_container" ref="map"></div>
        </div>

        <template #footer>
            <div style="width: 100%; display: flex">
                <span v-if="location"
                    >{{ location.city }}/{{ location.district }}/{{location.town}}/{{ location.street }}</span
                >
                <span style="flex: 1"></span>
                <el-button type="default"  @click="handleCancel"
                    >取消</el-button
                >
                <el-button type="primary"  @click="handleOk"
                    >确定</el-button
                >
            </div>
        </template>
    </my-dialog>
</template>

<script>
let map;

export default {
    name: "MyMapDlg",
    emits: ["selected"],
    data() {
        return {
            state: {
                dlgVisible: false,
            },
            search: "",
            location: null,
            city: "东莞市",
            point: null,
            title: "",
        };
    },
    methods: {
        open(city, point, addr) {
            if(point){
                this.convertPoint(point, 3,5).then(p=>{
                    this.innerOpen(city,p,addr);
                })
            }else{
                this.innerOpen(city, point, addr);
            }
        },
        innerOpen(city, point, addr){
            this.city = city || "东莞市";
            this.location = null;
            this.point = point;
            //this.search = (addr || "").replace(/\//g,'');
            this.search = addr || "";
            this.state.dlgVisible = true;
            if (map) {
                if (point) {
                    map.centerAndZoom(point);
                    map.addMark(point, title, false);
                } else if (addr) {
                    this.handleSearch();
                }
            } else {
                this.initMap();
            }

        },

        close() {
            this.state.dlgVisible = false;
        },

        handleSearch() {
            this.location = null;
            var me = this;
            var local = new BMap.LocalSearch(map, {
                //renderOptions: { map: map, autoViewport: true, pageCapacity: 8 },
                onSearchComplete: function (res) {
                    map.clearOverlays();
                    var pps = [];
                    const mm = res.Br || res.Cr;
                    for (let ix = 0; ix < mm.length; ix++) {
                        let item = mm[ix];
                        pps.push(item.point);
                        me.addMark(item.point, item.title, false);
                    }
                    map.setViewport(pps);
                },
            });
            local.search(this.search);
        },

        addMark(point, title, canDrag) {
            var me = this;

            map.centerAndZoom(point, 16);
            let mark = new BMap.Marker(point, {
                enableDragging: canDrag,
                title: title,
            });
            map.addOverlay(mark);
            // mark.enableDragging();
            // mark.addEventListener("dragend",function(e){
            //     //alert("当前位置：" + e.point.lng + ", " + e.point.lat); 
            //     me.setLocation(e)
            // });
            mark.addEventListener("click", function (e) {
                me.setLocation(e)
            });
            return mark;
        },

        setLocation(e){
            var myGeo = new BMap.Geocoder({ extensions_town: true });
            var me = this;
                    // 根据坐标得到地址描述
            myGeo.getLocation(e.point, function (result) {
                if (result) {
                    let addr = { ...result.addressComponents };
                    addr.address = result.address;
                    addr.build = result.address;
                    addr.longitude = result.point.lng;
                    addr.latitude = result.point.lat;
                    me.location = addr;
                    const title = `${addr.city}${addr.town}${addr.street}${addr.streetNumber}`;
                    var opts = {
                        width: 250, // 信息窗口宽度
                        height: 100, // 信息窗口高度
                        title: title, // 信息窗口标题
                    };
                    var infoWindow = new BMap.InfoWindow(
                        result.address,
                        opts
                    ); // 创建信息窗口对象
                    map.openInfoWindow(infoWindow, e.point);
                }
            });
        },

        /**
         * 定位获得当前位置信息
         * */
        getMyLocation() {
            var me = this;
            var geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(function (r) {
                if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                    me.addMark(r.point, "当前位置", true);
                } else {
                    alert("定位失败:" + this.getStatus());
                }
            });
        },

        showPosition(position) {
            this.position.latitude = position.lat;
            this.position.longitude = position.lng;
            this.position.city = position.city;
            this.setMapData(position.lat, position.lng);
        },
        //定位失败再请求定位，测试使用
        showErr() {
            console.log("定位失败，请重试！");
            this.getMyLocation();
        },

        initMap() {
            if (map) return;
            if (!this.$refs.map) {
                window.setTimeout(this.initMap, 100);
                return;
            }
            var me = this;
            map = new BMap.Map(this.$refs.map);
            window.setTimeout(function () {
                map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
                map.addControl(new BMap.NavigationControl());
                map.addControl(new BMap.ScaleControl());
                map.centerAndZoom(me.city, 16);

                if (me.search) {
                    me.handleSearch();
                }
            }, 100);
        },

        handleOk() {
            if (this.location) {
                console.log(this.location.longitude+","+ this.location.latitude)
                this.convertPoint(this.location,5,3).then(p=>{
                    this.location.latitude  = p.lat;
                    this.location.longitude = p.lng;
                    this.$server.call("/Area/findOrAdd", this.location, this.$refs.map)
                    .then((res) => {
                            this.$emit("selected", res);
                            this.state.dlgVisible = false;
                        });
                });
            }
        },
        convertPoint(p,from,to){
            //坐标转换 ,从百度bd09经纬度坐标 ---》GCJ02坐标（微信小程序中使用）
            /**
             * 坐标常量说明：
             * COORDINATES_WGS84 = 1, WGS84坐标
             * COORDINATES_WGS84_MC = 2, WGS84的平面墨卡托坐标
             * COORDINATES_GCJ02 = 3，GCJ02坐标
             * COORDINATES_GCJ02_MC = 4, GCJ02的平面墨卡托坐标
             * COORDINATES_BD09 = 5, 百度bd09经纬度坐标
             * COORDINATES_BD09_MC = 6，百度bd09墨卡托坐标
             * COORDINATES_MAPBAR = 7，mapbar地图坐标
             * COORDINATES_51 = 8，51地图坐标
            */
           from = from || 5;
           to = to || 3;

            var ggPoint = new BMap.Point(p.longitude,p.latitude);
            return new Promise((resolve, reject) => {
                const convert = new BMap.Convertor();
                var pointArr = [];
                pointArr.push(ggPoint);
                convert.translate(pointArr, from, to, function(data){
                    if(data.status==0){
                        resolve(data.points[0]);
                    }
                })
            });
        },
        handleCancel() {
            this.state.dlgVisible = false;
        },
    },
    created() {
        // if (!document.getElementById("__bmapid")) {
        //   let bmap_url =
        //     "//api.map.baidu.com/api?v=3.0&ak=" + this.$store.baidu_map_key;
        //   let bmap_api_dom = document.createElement("script");
        //   bmap_api_dom.charset = "utf-8";
        //   bmap_api_dom.src = bmap_url;
        //   bmap_api_dom.id = "__bmapid";
        //   document.head.appendChild(bmap_api_dom);
        // }
    },
    watch: {
        "state.dlgVisible": function (val) {
            if (val && !map) {
                this.initMap();
                if (!this.point && !this.search) {
                    this.getMyLocation();
                }
            }
        },
    },
};
</script>

<style scoped>
.index {
    width: 100%;
    height: 100%;
    display: flex;
    flex-flow: column;
}
.map_container {
    flex: 1;
    width: 100%;
    position: relative;
}
</style>